import { login } from '@/api/user'
import { getToken, getShareToken, setLoginData } from '@/utils/auth'
// import { Toast } from 'vant'

const state = {
  token: getToken(),
  loginList: JSON.parse(localStorage.getItem('loginList')) || {},
  profileList: JSON.parse(localStorage.getItem('profileList')) || {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_LOGINLIST: (state, loginList) => {
    state.loginList = loginList
  },
  SET_PRFILE_LIST: (state, profile) => {
    state.profileList = profile
  }
}

const actions = {
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(res => {
          const data = res.data
          const token = data['access_token']
          commit('SET_TOKEN', token)
          commit('SET_LOGINLIST', data)
          commit('SET_PRFILE_LIST', data.profile)
          localStorage.setItem('loginList', JSON.stringify(data))
          localStorage.setItem('profileList', JSON.stringify(data.profile))
          setLoginData(data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
